/*
 * @(#)ExceptionHandlerPage.java 2021年3月10日
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.config;

import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.nuctech.common.bean.C;
import com.nuctech.common.bean.R;
import com.nuctech.common.utils.ObjectMapperUtils;

import cn.hutool.http.ContentType;

/**
 * 自定义Sentinel异常返回信息
 * 
 * @author lilu
 * @date 2021年3月10日
 * @since 1.0.0
 */
@Component
public class ExceptionHandlerPage implements BlockExceptionHandler {
	
	private static final String DEFAULT_BLOCK_MSG_PREFIX = "Sentinel: ";

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setStatus(C.TOO_MANY_REQ.getCode());
        response.setContentType(ContentType.JSON.toString(StandardCharsets.UTF_8));
        
        R<?> r = R.fail();
        
        if (e instanceof FlowException) {
			r = R.fail(C.TOO_MANY_REQ, DEFAULT_BLOCK_MSG_PREFIX + "接口被限流");
		} else if (e instanceof DegradeException) {
			r = R.fail(C.TOO_MANY_REQ, DEFAULT_BLOCK_MSG_PREFIX + "接口被降级");
		} else if (e instanceof ParamFlowException) {
			r = R.fail(C.TOO_MANY_REQ, DEFAULT_BLOCK_MSG_PREFIX + "接口参数限流异常");
		} else if (e instanceof AuthorityException) {
			r = R.fail(C.TOO_MANY_REQ, DEFAULT_BLOCK_MSG_PREFIX + "接口授权异常");
		} else if (e instanceof SystemBlockException) {
			r = R.fail(C.TOO_MANY_REQ, DEFAULT_BLOCK_MSG_PREFIX + "系统负载异常");
		}
        
        PrintWriter out = response.getWriter();
        out.print(ObjectMapperUtils.toJSON(r));
        out.flush();
        out.close();
	}

}
